//
//  GrowthViewController.m
//  Growth
//
//  Created by Hobo.Chen on 12/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GrowthViewController.h"

#import "ContentUnitViewController.h"

#import "TimelineViewController.h"

#import "TLTrendsViewController.h"

#import "ChannelViewController.h"
#import "CHRecommendViewController.h"
#import "CHListViewController.h"
#import "MenuViewController.h"

#import "AllChannelViewController.h"

#import "LoginViewController.h"
#import "RegistViewController.h"

#import "ProfileViewController.h"


#import"BmiViewController.h"
#import"FoodViewController.h"
#import"WritingRecordViewController.h"

#import "AlbumViewController.h"


#import "MyShoucangViewController.h"
#import "familyViewController.h"


#import "bapooViewController.h"

#import "pictureWallViewController.h"

#import "PersonalLetterViewController.h"


#import "UserSettingViewController.h"
#import "TimelineSettingViewController.h"
#import "SystemMessageViewController.h"
#import "ModifyKeyViewController.h"

#import "TLDetailViewController.h"


#import "pictureWallViewController.h"
#import "RegistViewController.h"
#import "SDImageView+SDWebCache.h"

#import "HaveAttentionViewController.h"
#import "timelineListViewController.h"

#import "diaryContentView.h"

#import "shareToDoViewController.h"

#import "addAnniversayVIewController.h"

//test
#import "KNFirstViewController.h"

//path
#import "DDMenuController.h"


//
#import "guideViewController.h"


//
#import "FriendsViewController.h"

static WebConnectionArray *userTiemlineMember_connection;

static WebConnectionArray *systemMessage_connection;

@interface GrowthViewController (Private)


- (void)loadLoginView;
- (void)loadRegistView;


@end



@implementation GrowthViewController

@synthesize isMenuEnable;

@synthesize menuViewController;
@synthesize contentViewController;


//controllers
@synthesize menuController;
@synthesize mainController;
@synthesize leftController;
@synthesize freindsNewsController;
@synthesize myFamilyViewController;
@synthesize toolBoxViewController;

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
//	UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
//	accelerometer.delegate = self;
//	accelerometer.updateInterval =  kUpdateInterval;
	
	isMenuEnable = NO;
    
    
	
	//测试使用，有需要的继续添加
	/*
	 1、Login界面
	 2、Timeline界面
	 3、频道界面
	 */

	NSInteger viewIndex = 4;


//    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) { //记住帐号直接进主页
//        viewIndex = 1;
//    }
    
//    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"isFirstInApp"]) {
//        viewIndex = 2;
//        
//    }

    
    
	switch (viewIndex) {
		case 1:
		{
			
    
            [self userLoginSuccess];
            
			break;
		}
		case 2:
		{
			
            
			break;
		}
		case 3:
		{
			[self userLoginSuccess];
			break;
		}
 
			case 4:
        {
            
            if (![[NSUserDefaults standardUserDefaults] valueForKey:@"isFirstInApp"]) { //第一次进程序
             //   [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"isFirstInApp"];
                
                guideViewController *viewController = [[guideViewController alloc] init];
                viewController.delegate=self;
                [self.view insertSubview:viewController.view atIndex:0];
                
            }
            else{
           
                [self toImageWall];
                
            }
            break;
        }
            break;
		default:
			break;
	}
	
   // [self showMenuView];
    [super viewDidLoad];
}



/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    
    [super dealloc];
    [mainController release];
    [leftController release];
    [freindsNewsController release];
    [myFamilyViewController release];
    [toolBoxViewController release];
    
    if (userTiemlineMember_connection != nil) {
         userTiemlineMember_connection.connectionDelegate = nil;
        [userTiemlineMember_connection release];
        userTiemlineMember_connection = nil;
    }
    if (systemMessage_connection != nil) {
        systemMessage_connection.connectionDelegate = nil;
        [systemMessage_connection release];
        systemMessage_connection = nil;
    }
   
    
}

#pragma mark -Menu
-(void)showAllMenu{
    
   
		menuViewController = [[MenuViewController alloc] init];
		menuViewController.delegate = self;
    menuViewController.view.hidden = YES;
    [menuViewController.view setFrame:CGRectMake(0, 0, 320, 445)];
    //  
    menuViewController.view.userInteractionEnabled = NO;   
    
       
      [menuController.view insertSubview:menuViewController.view atIndex:kTopViewIndex+10];
     //[menuController.view bringSubviewToFront:menuViewController.view];


}

-(void)hideRecordMenu{
    
    // [menuViewController.view setFrame:CGRectMake(0, 0, 320, 400)];
    menuViewController.view.hidden = YES;
   // menuViewController.view.userInteractionEnabled = NO;
    
}

-(void)showRecordMenu{
    
   // [menuViewController.view setFrame:CGRectMake(0, 0, 320, 400)];
    menuViewController.view.hidden = NO;
   // menuViewController.view.userInteractionEnabled = YES;
    
}

-(void)showCamera{
    
   
    [menuViewController showCamera:nil];
    
}



-(void)setImagePickerPresentController:(UIImagePickerController *)imageController{

    if (menuViewController != nil) {
        [menuController.view bringSubviewToFront:menuViewController.view];
         [menuViewController presentModalViewController:imageController animated:YES] ; 
       // [menuController.rootViewController presentModalViewController:imageController animated:YES];
        
    }
   
    
}

#pragma mark -Load View 
#pragma mark -页面链接

//第三方绑定页面
-(void)loadThirdPartView{
    
    ThirdPartLoginViewController *loginViewController = [[ThirdPartLoginViewController alloc] init];
	loginViewController.delegate = self;
    loginViewController.pushViewDelegate = self;
	//[self.view insertSubview:loginViewController.view atIndex:kSystemViewIndex];
	
  //  [self addNextViewWith:loginViewController forView:self.contentViewController.view animationType:kPushRight insertIndex:kContentViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:loginViewController animated:YES];
    

    
}

//登陆页面
- (void)loadLoginView{
	isMenuEnable = NO;
	
	LoginViewController *loginViewController = [[LoginViewController alloc] init];
	loginViewController.delegate = self;
    loginViewController.pushViewDelegate = self;
	
	
   // 
    
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] != nil) {
        
         [appDelegate.navigationController pushViewController:loginViewController animated:YES];
    }
    else{
        
        [self addNextViewWith:loginViewController forView:self.view animationType:kPushRight insertIndex:kTopViewIndex+1];
        
    }
    
    
   
    
   
}

//注册
-(void)loadRegistView{
    RegistViewController *viewController = [[RegistViewController alloc] init];
    viewController.pushViewDelegate = self;
    viewController.delegate = self;
 //   [self addNextViewWith:viewController forView:self.view animationType:kPushRight insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:viewController animated:YES];
    
      
}

//退出
-(void)logoutAction{
    
    //退出到登陆界面
    [self loadLoginView];

    
    
    if (self.contentViewController != nil) {
        [contentViewController.view removeFromSuperview];
       
        [contentViewController release];
        contentViewController = nil; 
        
           }
    
    
    //删除缓存
    
    [[SDDataCache sharedDataCache:kImageTypeTLTrend] clearDisk];
    [[SDDataCache sharedDataCache:kImageTypeLetter] clearDisk];
    [[SDDataCache sharedDataCache:kImageTypeTimeline] clearDisk];
    [[SDDataCache sharedDataCache:kImageTypeUserInfo] clearDisk];
     [[SDDataCache sharedDataCache:kImageTypeFriendInfo] clearDisk];
    [[SDDataCache sharedDataCache:kImageTypeFamilyInfo] clearDisk];
    
   // [[SDDataCache sharedDataCache:kImageTypeChannel] clearDisk];
    
    //删除时间轴头部背景
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"familyImage"];
    
    PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
    
    
   // NSString *sql = [NSString stringWithFormat:@"delete from DiaryViews where id = %d",[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]];
    NSString *sql = [NSString stringWithFormat:@"delete from DiaryViews",[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]];

    [databaseEngine executeSQL:sql];
    
    NSString *sql2 = [NSString stringWithFormat:@"delete from DiaryView"];
    [databaseEngine executeSQL:sql2];
    
    NSString *sql3 = [NSString stringWithFormat:@"delete from TimelineId"];
    [databaseEngine executeSQL:sql3];
    
    NSString *sql4 = [NSString stringWithFormat:@"delete from FamilyMembers"];
    [databaseEngine executeSQL:sql4];

    NSString *sql5 = [NSString stringWithFormat:@"delete from TimelineInfo"];
    [databaseEngine executeSQL:sql5];
    

    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"timelineId"]; 

    //[databaseEngine executeSQL:sql];

      
   
  
    
       
}


//到图片墙
-(void)toImageWall{
    
   
    pictureViewController = [[pictureWallViewController alloc] init];
    pictureViewController.delegate=self;
  //  [self.view insertSubview:pictureViewController.view atIndex:0];
    [self addNextViewFlipWith:pictureViewController forView:self.view isRight:YES insertIndex:kContentViewIndex];
    
}


//他人宝宝的时间轴
- (void)toBabyTimelineView:(id)sender userId:(int)uid{
    UIButton *button = (UIButton *)sender;
    
    otherTimelineViewController *ViewController = [[otherTimelineViewController alloc] initWithTimelineId:button.tag userId:uid];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
    
 //   [self addNextViewWith:ViewController forView:menuController.view animationType:kPushUp insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:ViewController animated:YES];

    
}


//频道
- (void)toChannelView:(id)sender{
	UIButton *button = (UIButton *)sender;
	
	NSInteger tag = button.tag;
	NSString *chId = [NSString stringWithFormat:@"%d", tag];
	
    if (contentViewController != nil) {
		//当前不是频道，进入指定默认频道，可进行默认设置
        if (contentViewController.contentType != ChannelContent) {
            [contentViewController.view removeFromSuperview];
            [contentViewController release];
            
            //加载频道
            contentViewController = [[ChannelViewController alloc] initWithId:chId];
            contentViewController.delegate = self;
			
            [self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
            
        }
		else {
			
			ChannelViewController *chViewController = (ChannelViewController *)contentViewController;
			NSString *curChId =  chViewController.channelId;
			//现在的频道不是所选频道，重新加载
			if (![curChId isEqualToString:chId]) {
				[contentViewController.view removeFromSuperview];
				[contentViewController release];
				
				//加载频道
				contentViewController = [[ChannelViewController alloc] initWithId:chId];
				contentViewController.delegate = self;
				
				[self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
			}
		}
        
		
    }
	else {
		//加载频道
		contentViewController = [[ChannelViewController alloc] initWithId:chId];
		contentViewController.delegate = self;
		
		[self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
	}
    
	isMenuEnable = YES;
}


//身高体重
-(void)toBmiRecordView:(id)sender{
    
	isMenuEnable = NO;
    
	BmiViewController *ViewController = [[BmiViewController alloc] init];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
    // [ViewController.view setFrame:CGRectMake(0, 44, 320, 480)];
	//[self.view insertSubview:ViewController.view atIndex:kSystemViewIndex];
	
    [self addNextViewWith:ViewController forView:self.menuController.view animationType:kPushUp insertIndex:kTopViewIndex];
    
	
}

//食物记录
-(void)toFoodRecordView:(id)sender{
	
   		//加载食物记录
    FoodViewController *ViewController = [[FoodViewController alloc] init];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
  
    [self addNextViewWith:ViewController forView:menuController.view animationType:kPushUp insertIndex:kTopViewIndex];
    
}

//便便
-(void)toBianbianView:(id)sender{
	
   	isMenuEnable = NO;
  
    
	//加载食物记录
    bapooViewController *ViewController = [[bapooViewController alloc] init];
	ViewController.pushViewDelegate = self;
    ViewController.delegate  = self;
    
    [self addNextViewWith:ViewController forView:menuController.view animationType:kPushUp insertIndex:kTopViewIndex];
	
}

//文字记录
-(void)toWritingRecordView:(id)sender{
	
  	isMenuEnable = NO;
    
	WritingRecordViewController *ViewController = [[WritingRecordViewController alloc] init];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
	
    [self addNextViewWith:ViewController forView:menuController.view animationType:kPushUp insertIndex:kTopViewIndex];
    
}


//文字
-(void)toPhotoView:(UIImage *)image{
	
	isMenuEnable = NO;
	
	WritingRecordViewController *ViewController = [[WritingRecordViewController alloc] initWithImage:image];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
    
    [self addNextViewWith:ViewController forView:menuController.view animationType:kPushUp insertIndex:kTopViewIndex];
    
    
}


//批量上传
- (void)toPhotosUpload:(id)sender
{
    isMenuEnable = NO;
	
	AlbumViewController *ViewController = [[AlbumViewController alloc] init];

    [self addNextViewWith:ViewController forView:menuController.view animationType:kPushUp insertIndex:kTopViewIndex];
}

//我的私信
-(void)toMyLetterView:(id)sender{
    
    //屏蔽tap事件
    [menuController.tap setEnabled:NO];
    
    PersonalLetterViewController *viewController = [[PersonalLetterViewController alloc] init];
	viewController.pushViewDelegate = self;
    viewController.delegate = self;
  //  [self addNextViewWith:viewController forView:menuController.view animationType:kPushRight insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:viewController animated:YES];
    
    
}

//个人设置
-(void)toUserSettingView:(id)sender{
    
       UserSettingViewController * viewController = [[UserSettingViewController alloc]init];
    
   // [self addNextViewWith:viewController forView:menuController.view  animationType:kPushRight insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:viewController animated:YES];
    
}


//我的宝宝列表
-(void)toTimelineListModifyView:(id)sender{
    
    [self setMenuControllerTapEnabel:NO];
    
    timelineListViewController * viewController = [[timelineListViewController alloc]init];
    viewController.pushViewDelegate = self;
    viewController.delegate = self;
    
  //  [self addNextViewWith:viewController forView:menuController.view animationType:kPushRight insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:viewController animated:YES];

    
}


//宝宝设置
-(void)toTimelineSettingView:(NSDictionary *)timelineDict{
    
    [self setMenuControllerTapEnabel:NO];
    
    TimelineSettingViewController *viewController = [[TimelineSettingViewController alloc]initWithTimelineDict:timelineDict];
    viewController.pushViewDelegate = self;
    viewController.delegate = self;
    
    
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"]) {
        
         [appDelegate.navigationController pushViewController:viewController animated:YES];
    }
    else{
        
        [self addNextViewWith:viewController forView:self.view animationType:kPushRight insertIndex:kTopViewIndex];
    }
   
    
}

//修改密码
-(void)toModifyKeyView{
    
    [self setMenuControllerTapEnabel:NO];
    ModifyKeyViewController *viewController = [[ModifyKeyViewController alloc]init];
    viewController.pushViewDelegate = self;
    viewController.delegate = self;
    
  //  [self addNextViewWith:viewController forView:menuController.view animationType:kPushRight insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:viewController animated:YES];

    
}

//我的关注
- (void)toFriendsView:(id)sender{
	isMenuEnable =NO;
    
	HaveAttentionViewController *ViewController=[[HaveAttentionViewController alloc] init];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
  //  [self addNextViewWith:ViewController forView:menuController.view animationType:kPushRight insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:ViewController animated:YES];

    
}


// 更多列表
- (void)toProfileView:(id)sender{
	isMenuEnable = NO;
    
   	
	if (contentViewController != nil) {
        if (contentViewController.contentType != ProfileView) {
            [contentViewController.view removeFromSuperview];
            [contentViewController release];
            
            //加载时间轴  
            contentViewController = [[ProfileViewController alloc] init];
			contentViewController.delegate = self;
			contentViewController.pushViewDelegate = self;
            
            [self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
            
            
            if(menuViewController == nil){
                menuViewController = [[MenuViewController alloc] init];
                menuViewController.delegate = self;
                menuViewController.view.hidden = YES;
                [menuViewController.view setFrame:CGRectMake(0, 0, 320, 445)];
                
            }
            [self.contentViewController.contentView addSubview:menuViewController.view];
            
            
            
            
        }
    }
	else {
		
		contentViewController = [[ProfileViewController alloc] init];
		contentViewController.delegate = self;
		
		[self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
        
              
        if(menuViewController == nil){
            menuViewController = [[MenuViewController alloc] init];
            menuViewController.delegate = self;
            menuViewController.view.hidden = YES;
            [menuViewController.view setFrame:CGRectMake(0, 0, 320, 445)];
            
        }  
        [self.contentViewController.contentView addSubview:menuViewController.view];
        
        
	}
    
}

- (void)toCHRecommendView:(id)sender{
	if (contentViewController != nil) {
        if (contentViewController.contentType != CHRecommendContent) {
            [contentViewController.view removeFromSuperview];
            [contentViewController release];
            
            //加载时间轴
            contentViewController = [[CHRecommendViewController alloc] init];
			contentViewController.delegate = self;
            
            [self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
            
        }
    }
	else {
		//加载时间轴
		contentViewController = [[CHRecommendViewController alloc] init];
		contentViewController.delegate = self;
		
		[self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
	}
	
	isMenuEnable = YES;
	
}


//频道列表
- (void)toCHListView:(id)sender{
	if (contentViewController != nil) {
        if (contentViewController.contentType != AllCHContent) {
            [contentViewController.view removeFromSuperview];
            [contentViewController release];
            
            
            contentViewController = [[AllChannelViewController alloc] initWithCHid:@"2"];
            contentViewController.delegate = self;
            
            [self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
            
        }
    }
	else {
		
		contentViewController = [[AllChannelViewController alloc] init];
		contentViewController.delegate = self;
		
		[self.view insertSubview:contentViewController.view atIndex:kContentViewIndex];
	}
	
	isMenuEnable = NO;
	
}


//我的收藏
- (void)toMyShoucang:(id)sender{
    
    [self setMenuControllerTapEnabel:NO];
    
    MyShoucangViewController *ViewController = [[MyShoucangViewController alloc] init];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
    
   // [self addNextViewWith:ViewController forView:menuController.view animationType:kPushRight insertIndex:kSystemViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:ViewController animated:YES];
    
}


//推荐关注
-(void)toMyAttentionView{
    
    
    MyAttentionViewController *ViewController = [[MyAttentionViewController alloc] init];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
	
    
    
    [self addNextViewWith:ViewController forView:menuController.view animationType:kPushRight insertIndex:kSystemViewIndex];
    
    
}

//我的关注
-(void)toHaveAttentionView{
    
    HaveAttentionViewController *ViewController = [[HaveAttentionViewController alloc] init];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
    
    [self addNextViewWith:ViewController forView:menuController.view animationType:kPushRight insertIndex:kSystemViewIndex];
    
    
}


//我的家人
-(void)toFamilyView:(id)sender{
    
   // [self setMenuControllerTapEnabel:NO];
    
    self.freindsNewsController.view.hidden = YES;
    self.toolBoxViewController.view.hidden = YES;
    
    if (self.myFamilyViewController == nil) {
        
        myFamilyViewController = [[FamilyViewController alloc]  init];
        
        //加在主页上
      //  [self addNextViewWith:myFamilyViewController forView:mainController.contentView animationType:kPushUp insertIndex:kTopViewIndex];
        
        [mainController.contentView addSubview:myFamilyViewController.view];
        
    }
    else{
        if (self.myFamilyViewController.view.hidden == YES) {
            
            self.myFamilyViewController.view.hidden = NO;
            [mainController.view bringSubviewToFront:myFamilyViewController.view];
        }
    }
    
    [mainController.contentView bringSubviewToFront:mainController.buttomBar];
    
    
}




//游客日志详情
-(void)toDiaryContentView:(int)did{
    
    
    diaryContentView *ViewController = [[diaryContentView alloc] initWithDiaryId:did ];
	ViewController.pushViewDelegate = self;
    ViewController.delegate = self;
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
   
    
    if (appDelegate.navigationController) {
        
        [appDelegate.navigationController pushViewController:ViewController animated:YES];   
             
    }
    else{
        
        [self addNextViewWith:ViewController forView:self.view animationType:kPushUp insertIndex:kTopViewIndex];
        
        
    }
    
    
}


//记录日志详情
- (void)toTLTrendDetailView:(NSString *)uid array:(NSMutableArray *)array row:(int)row type:(NSString *)type{
    
    TLDetailViewController *detailViewController = [[TLDetailViewController alloc] initWithId:uid timelinedict:array pageNo:row type:type];
    
    detailViewController.delegate = self;
    
 
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];

    [appDelegate.navigationController pushViewController:detailViewController animated:YES];
    
}



//个人主页
-(void)toUserView:(id)sender{
    
    UIButton *button = (UIButton *)sender;
    
//    UserViewController *userViewController = [[UserViewController alloc]initWithUserId:button.tag];
//    
//    
// 
//    
//    GrowthAppDelegate *appDelegate = 
//    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
//    [appDelegate.navigationController pushViewController:userViewController animated:YES];
    
    CLog(@"user button tag %d",button.tag );
    
    PersonalViewController *ViewController = [[PersonalViewController alloc]initWithUserId:button.tag];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:ViewController animated:YES];

    
}


//记录计划任务
-(void)toShareToDoView{
    
    shareToDoViewController *ViewController = [[shareToDoViewController alloc]  init];
    ViewController.delegate = self;
    ViewController.pushViewDelegate = self;
    
   // [self addNextViewWith:ViewController forView:menuController.view animationType:kPushUp insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:ViewController animated:YES];

    
    
}


//我的计划任务列表
-(void)toplanListView{
    
    [self setMenuControllerTapEnabel:NO];
    
    planListViewController *ViewController = [[planListViewController alloc]  init];
    ViewController.delegate = self;
    ViewController.pushViewDelegate = self;
    
  //  [self addNextViewWith:ViewController forView:menuController.view animationType:kPushRight insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:ViewController animated:YES];

    
}

//大事件
-(void)toAnniversaryView{
    
    [self setMenuControllerTapEnabel:NO];
    
    anniversaryViewController *ViewController = [[anniversaryViewController alloc]  init];
    ViewController.delegate = self;
    ViewController.pushViewDelegate = self;
    
   // [self addNextViewWith:ViewController forView:menuController.view animationType:kPushRight insertIndex:kTopViewIndex];
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:ViewController animated:YES];

    
    
}


//到工具箱
-(void)toToolBox:(id)sender{
    
    self.myFamilyViewController.view.hidden = YES;
    self.freindsNewsController.view.hidden = YES;
    
    if (self.toolBoxViewController == nil) {
        
        toolBoxViewController = [[ToolBoxViewController alloc]  init];
        
        //加在主页上
       // [self addNextViewWith:toolBoxViewController forView:mainController.contentView animationType:kPushUp insertIndex:kTopViewIndex];
        [mainController.contentView addSubview:toolBoxViewController.view];
        
    }
    else{
        if (self.toolBoxViewController.view.hidden == YES) {
           
            self.toolBoxViewController.view.hidden = NO;
            [mainController.view bringSubviewToFront:self.toolBoxViewController.view ];
        }
    }
    
    [mainController.contentView bringSubviewToFront:mainController.buttomBar];

    
}

//所有动态
- (void)toTLTrendsView:(id)sender{
    
    if (self.freindsNewsController == nil) {
        
        freindsNewsController = [[TLTrendsViewController alloc]  init];
        freindsNewsController.delegate = self;
        freindsNewsController.pushViewDelegate = self;
    
    //加在主页上
        //[self addNextViewWith:freindsNewsController forView:mainController.contentView animationType:kPushUp insertIndex:kTopViewIndex];
        [mainController.contentView addSubview:self.freindsNewsController.view];

    }
    else{
        if (self.freindsNewsController.view.hidden == YES) {
            self.myFamilyViewController.view.hidden = YES;
            self.toolBoxViewController.view.hidden = YES;
            self.freindsNewsController.view.hidden = NO;
            [mainController.view bringSubviewToFront:self.freindsNewsController.view ];
        }
    }
        
    [mainController.contentView bringSubviewToFront:mainController.buttomBar];
	
}

//回主页

- (void)toMainView{
    
    if (self.freindsNewsController != nil) {
        self.freindsNewsController.view.hidden = YES;
        
    }
   
    if (self.myFamilyViewController != nil) {
        self.myFamilyViewController.view.hidden = YES;
    }
    
    if (self.toolBoxViewController.view != nil) {
        self.toolBoxViewController.view.hidden = YES;
    }
    
}

//添加大事件
-(void)toAddAnniversaryView{
    addAnniversayVIewController *ViewController = [[addAnniversayVIewController alloc]  init];
    ViewController.delegate = self;
    ViewController.pushViewDelegate = self;
     
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:ViewController animated:YES];

    
    
}


//回主页
- (void)toTimelineView:(id)sender{
    
    //
    if (menuController != nil) {
        
        if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
            
            int uid = [[[NSUserDefaults standardUserDefaults]valueForKey:@"userId"] intValue];
            int tid = [[[NSUserDefaults standardUserDefaults]valueForKey:@"timelineId"] intValue];
            
             [mainController.TLTrendArray removeAllObjects];
            [mainController loadTimelineData:uid timelineId:tid pageNo:1 pageSize:10];
            [mainController loadTimelineMember:uid];
            
           
            
            
        }
        else{ //游客登录
            
            [mainController.tableView reloadData];
            
        }
        [mainController.tableView setContentOffset:CGPointMake(0, 0)];
        [self toMainView];
        // [menuController showRootController:YES];
        
    }
    else{
        [self userLoginSuccess];
        
    }
    
	
	isMenuEnable = YES;
    
    
}




#pragma mark -Menu Delegate

//隐藏菜单
- (void)hideMenu{
	
	[self showMenuView];
}


#pragma mark - Login Delegate
- (void)userLoginSuccess{
    
    
//    GrowthAppDelegate *delegate = (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
//    [delegate loadMainView];
//    
//    return; 
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"isFirstInApp"];
    
    
    if (pictureViewController != nil) {
        [pictureViewController.view removeFromSuperview];
        [pictureViewController release];
        pictureViewController = nil;
        
        [[SDDataCache sharedDataCache:kImageTypeImageWall] clearDisk];
        
    }
	
    //把一些不要的缓存图片删除
    [[SDDataCache sharedDataCache:kImageTypeLetter] clearDisk];
    //[[SDDataCache sharedDataCache:kImageTypeUserInfo] clearDisk];
    
        
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
   
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] != nil) {
        
        //[appDelegate.window addSubview:appDelegate.navigationController.view];
        [appDelegate loadMainView];
        
    }
    
    
    
 
    
    [self showAllMenu];
    
    
    
}

-(void)loadTimelineInfo{
    
    //下载可管理时间轴
    int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
    
    NSMutableURLRequest * request = [WebRequest userTiemlineMemberRequestWith:[NSString stringWithFormat:@"%d",uid]];
	
	CLog(@"request %@", request);
	//WebConnectionArray *connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:@"TimelineId"];
    if (userTiemlineMember_connection != nil) {
        userTiemlineMember_connection.connectionDelegate = nil;
    }
    userTiemlineMember_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:@"TimelineId"];
    
    
}



#pragma mark PushViewDelegate
- (void)pushViewBackAction{
	isMenuEnable = YES;
}




//更新朋友数量
-(void)updateAttentionNum{
    
    if (leftController) {

        [leftController loadAttentionCount];
    }
    
}

#pragma mark -加速计 Delegate

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
	static NSInteger shakeCount = 0;
    static NSDate *shakeStart;
	
	if (!isMenuEnable) {
		return;
	}
    
    NSDate *now = [[NSDate alloc] init];
    NSDate *checkDate = [[NSDate alloc] initWithTimeInterval:1.5f sinceDate:shakeStart];
    
    if ([now compare:checkDate] ==NSOrderedDescending || shakeStart == nil) {
        shakeCount = 0;
        [shakeStart release];
        shakeStart = [[NSDate alloc] init];
    }
    
    [now release];
    [checkDate release];
    
    //CLog(@"acceleration x:%f, y:%f, z:%f", acceleration.x, acceleration.y, acceleration.z);
    
    if (fabsf(acceleration.x) > kAccelerationThreshold||
        fabsf(acceleration.y) > kAccelerationThreshold||
        fabsf(acceleration.z) > kAccelerationThreshold) {
        shakeCount++;
        if (shakeCount >2) {
            shakeCount = 0;
            [shakeStart release];
            shakeStart = [[NSDate alloc] init];
            
                            //[self showMenuView];
            
            
            CLog(@"Shake!");
        }
    }
    
	
}


#pragma mark - system message

-(void)systemMessage{
    
    //5 minute request 
   	[NSTimer scheduledTimerWithTimeInterval:600 target:self selector:@selector(requestSystemMessage) userInfo:nil repeats:NO];
    
}

-(void)requestSystemMessage{
    
    int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];

    NSMutableURLRequest * request = [WebRequest systemMessageCountRequestWith:[NSString stringWithFormat:@"%d",uid]];
	
	CLog(@"request %@", request);
	//WebConnectionArray *connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    if (systemMessage_connection != nil) {
        systemMessage_connection.connectionDelegate = nil;
    }
    systemMessage_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];

    
    //未读私信数量请求
    
//	NSMutableURLRequest * _request = [WebRequest unreadLetterCountRequestWith:[NSString stringWithFormat:@"%d",uid]];
//	
//	CLog(@"request %@", _request);
//	WebConnectionArray *_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
//    

}



#pragma mark -WebConnection delegate

- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    CLog(@"info %@",  dict);
       
       if (dict==nil) {
        return;
    }
    
    CLog(@"GrowthViwController  url %@", url);
    
      int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
    
    
     /*****   可管理时间轴  *************/
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/timeline/menu/?uid=%d",MYBASEURL, uid]]) 
    {
        
          //登陆成功
            [self userLoginSuccess];

        if ([[dict objectForKey:@"object"] count] >0) {  //保存tid
              NSDictionary *timelineDict = [[dict objectForKey:@"object"] objectAtIndex:0];
        
             [[NSUserDefaults standardUserDefaults] setValue:[timelineDict objectForKey:@"id"] forKey:@"timelineId"];
                      
            
            /*********  查询是否有本地记录需要上传 begin  ********/
            if ([[NSUserDefaults standardUserDefaults] valueForKey:@"localRecordCount"]) {
                
                int localRecordCount = [[[NSUserDefaults standardUserDefaults]valueForKey:@"localRecordCount"] intValue];
                if (localRecordCount > 0) { //有离线记录
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"本地记录会占用手机存储空间，是否上传服务器？" 
                                                                   delegate:self 
                                                          cancelButtonTitle:@"取消" otherButtonTitles:nil];
                    [alert addButtonWithTitle:@"上传"];
                    
                    
                    [alert show];
                    [alert release];
                    
                }
            }

            /**********   end   *************************/
            
        }
        return;
        
    }
    
      
     /*****    上传本地记录  *************/
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/diary/create",MYBASEURL]]) {//成功上传记录
        
        if ([dict objectForKey:@"object"]) {
            
            
            int localRecordCount = [[[NSUserDefaults standardUserDefaults] valueForKey:@"localRecordCount"] intValue];
            
            if (localRecordCount>0) { //删除该条记录
                
                PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
                NSString *mysql = [NSString stringWithFormat:@"delete from LocalRecord where id=%d",localRecordCount];
                [databaseEngine executeSQL:mysql];

                
                localRecordCount--;
                [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:localRecordCount] forKey:@"localRecordCount"];
                
            }
                        
            if (localRecordCount == 0) {//本地记录上传完毕 ，清除本地记录
                
                [LoadingView hideWithAnimated:YES];
                  PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
                NSString *mysql = [NSString stringWithFormat:@"delete from LocalRecord"];
                [databaseEngine executeSQL:mysql];
                
                [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:0] forKey:@"localRecordCount"];
                
                //主页刷新数据
                int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
                [mainController loadTimelineData:uid timelineId:tid  pageNo:1 pageSize:10];
                [mainController loadTimelineInfo];
                
                //删除本地图片
                [[SDDataCache sharedDataCache:@"LocalRecord"] clearDisk];
                
                
            }
            

            
            if (localRecordCount > 0) {
                  PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
                
                NSString *sql = [NSString stringWithFormat:@"select * from LocalRecord where id=%d ",localRecordCount];
                
                NSString *JsonString = [databaseEngine selectJsonStringWithSQL:sql];
                
                
                if (JsonString != nil) {
                    
                    
                    NSData *JsonData = [JsonString dataUsingEncoding:NSUTF8StringEncoding];
                    
                    
                    NSError *error = nil;
                    NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:JsonData error:&error];
                    
                    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                    
                    
                    if ([[dictionary objectForKey:@"id"] intValue] == 0) { //timelineId
                        
                        if ([[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"]) {
                            int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
                            [dict setObject:[NSNumber numberWithInt:tid] forKey:@"id"];
                            
                        }
                        
                    }
                    
                    if ([[dictionary objectForKey:@"createdBy"] intValue] == 0) {
                        
                        if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
                            int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
                            [dict setObject:[NSNumber numberWithInt:uid] forKey:@"createdBy"];
                        }
                        
                    }
                    
                    NSString *_jsonStr =  [[CJSONSerializer serializer] serializeDictionary:dict];
                    
                    CLog(@"__jsonStr %@", _jsonStr);
                    
                    NSData *_jsonData = [_jsonStr dataUsingEncoding:NSUTF8StringEncoding];
                    
                    NSMutableURLRequest * request = [WebRequest diaryCreateRequestWith:_jsonData];

                    // [LoadingView  showMessageLoadingViewWith:@"上传中，请稍等......"];
                    CLog(@"request %@", request);
                   
                    
                }

                
                
            }
            
                                
        }
        
    }
   
}

- (void)connectionArrayError:(NSError *)error{
    
    if (! [[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"]) {
        
        [LoadingView showDurationMessageLoadingViewWith:10.0 message:@"请求失败，请检查网络连接状态！" ];   
        
    }
       
}


-(void)toMyMessageView:(int)messageCount{
    
    [self setMenuControllerTapEnabel:NO];
    
    SystemMessageViewController *viewController = [[SystemMessageViewController alloc]initWithMessageCount:messageCount];
   viewController.delegate = self;
    viewController.pushViewDelegate = self;
   //  [self addNextViewWith:viewController forView:menuController.view animationType:kPushRight insertIndex:kTopViewIndex ];
    
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:viewController animated:YES];
    
    
}



#pragma mark menucontroller tap
-(void)setMenuControllerTapEnabel:(BOOL)tap{
    
    if (menuController != nil) {
        
         [menuController.tap setEnabled:tap];
    }
   
    
}

#pragma mark release menuController
-(void)setMenuControllerNull{
    [menuController release];
    menuController = nil;
    
}


#pragma mark alert view delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) { //上传本地记录
        
        [LoadingView  showMessageLoadingViewWith:@"上传中，请稍等......"];
        [self upTheLocalDiary];
        
    }
    
}



#pragma mark 
#pragma mark 上传离线记录

-(void)upTheLocalDiary{
    
    int localRecordCount = [[[NSUserDefaults standardUserDefaults] valueForKey:@"localRecordCount"] intValue];
    
    CLog(@"localRecordCount %d", localRecordCount);
    
    if (localRecordCount <= 0) {
        return;
    }
    
    PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
            
        NSString *sql = [NSString stringWithFormat:@"select * from LocalRecord where id=%d ", localRecordCount];
        
        NSString *JsonString = [databaseEngine selectJsonStringWithSQL:sql];
            
                      
            if (JsonString != nil) {
                
                CLog(@"JsonString %@", JsonString);
                
                NSData *JsonData = [JsonString dataUsingEncoding:NSUTF8StringEncoding];
                
                                   
                NSError *error = nil;
                NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:JsonData error:&error];
                
                NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                
                             
                if ([[dictionary objectForKey:@"id"] intValue] == 0) { //timelineId
                    
                    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"]) {
                        int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
                        [dict setObject:[NSNumber numberWithInt:tid] forKey:@"id"];
                                              
                    }
                    
                }
                   
                if ([[dictionary objectForKey:@"createdBy"] intValue] == 0) {
                    
                    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
                        int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
                        [dict setObject:[NSNumber numberWithInt:uid] forKey:@"createdBy"];
                    }
                    
                }
               
                NSString *_jsonStr =  [[CJSONSerializer serializer] serializeDictionary:dict];
                
                CLog(@"__jsonStr %@", _jsonStr);
                
                 NSData *_jsonData = [_jsonStr dataUsingEncoding:NSUTF8StringEncoding];
                
                NSMutableURLRequest * request = [WebRequest diaryCreateRequestWith:_jsonData];
                
                CLog(@"request %@", request);
               
                
            }
            

    
}

#pragma mark 保存离线上传数据

-(void)saveRecordData:(NSString *)theBodyString{
    
    [LoadingView showDefaultLoadingView];

    PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
    
    //标记未上传记录条数
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"localRecordCount"]) {
        int localRecordCount = [[[NSUserDefaults standardUserDefaults] valueForKey:@"localRecordCount"] intValue];
        if (localRecordCount < 0) {
            localRecordCount = 0;
        }
        
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:localRecordCount+1] forKey:@"localRecordCount"];
    }
    else{
        
        [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"localRecordCount"];
        
    }
    
    NSString *sql = [NSString stringWithFormat:@"insert or replace into LocalRecord (id,json) values (%d, '%@')",[[[NSUserDefaults standardUserDefaults] valueForKey:@"localRecordCount"] intValue], theBodyString];
    
    [databaseEngine executeSQL:sql];
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"网络不好，已存储等待上传！"
                                                   delegate:self 
                                          cancelButtonTitle:@"确定" otherButtonTitles:nil];
    
    [alert show];
    [alert release];
          
    [self toTimelineView:nil];
    
}

#pragma mark 上传记录
-(void)sendRecordData:(NSString *)theBodyString{
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];;
	
	NSMutableURLRequest * request = [WebRequest diaryCreateRequestWith:jsonData];
	
	CLog(@"request %@", request);
	
   //WebConnection *diaryCreate_connection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
    
    [LoadingView showDefaultLoadingView];
       
}


@end
